package jf.jextn.converter;

import jf.jextn.JExtn;

public class BooleanConverter implements StringValueConverter<Boolean> {
    public final static BooleanConverter INSTANCE = new BooleanConverter();

    private String trueLiteral = null;
    private String falseLiteral = null;

    @Override
    public Boolean from(String value) {
        boolean bool = false;
        if (trueLiteral != null) {
            bool = trueLiteral.equals(value);
        } else {
            String val = value.toLowerCase();
            bool = "true".equals(val) ||
                    "1".equals(val) ||
                    "on".equals(val) ||
                    "y".equals(val) ||
                    "yes".equals(val);
        }

        return bool;
    }

    @Override
    public String to(Boolean o) {
        String out = null;
        if (trueLiteral != null) {
            out = o.booleanValue() ? trueLiteral : falseLiteral;
        } else {
            out = o.toString();
        }
        
        return out;
    }

    public void setTrueLiteral(String trueLiteral) {
        this.trueLiteral = JExtn.ifNullOrBlank(trueLiteral, "true");
    }

    public void setFalseLiteral(String falseLiteral) {
        this.falseLiteral = JExtn.ifNullOrBlank(falseLiteral, "false");
    }
}
